
#Region "Using Directives"

Imports System
Imports System.Collections.Generic
Imports System.Text

#End Region

Namespace C4F.DevKit.Bluetooth

    Namespace ServiceAndDeviceDiscovery

        ''' <summary>
        ''' Returns the network stream that allows users to control 
        ''' communication with a local service.
        ''' </summary>
        Public Class ServiceHandle

#Region "Private Members"

            ''' <summary>
            ''' Represents the socket used for communicating with clients.
            ''' </summary>
            Private serverSocket As Net.Sockets.Socket

#End Region

#Region "Constructor and Destructor"

            ''' <summary>
            ''' Initializes a ServiceHandle object.
            ''' </summary>
            ''' <param name="socket">socket for communicating with client.</param>
            Public Sub New(ByVal socket As Net.Sockets.Socket)

                Me.serverSocket = socket

            End Sub

            Protected Overrides Sub Finalize()

                Try

                    'Destructor for ServiceHandle which closes the socket connection.
                    Me.serverSocket.Close()

                Finally

                    MyBase.Finalize()

                End Try

            End Sub

#End Region

#Region "Public Functions"

            ''' <summary>
            ''' Determines if there are any connections pending on the socket.
            ''' </summary>
            ''' <returns>Returns true if connections are pending else returns 
            ''' false.</returns>
            Public Function ConnectionsPending() As Boolean

                Return Me.serverSocket.Poll(0, Net.Sockets.SelectMode.SelectRead)

            End Function

            ''' <summary>
            ''' Socket accepts connection and returns a network stream.
            ''' </summary>
            ''' <returns>A network stream which is used for communication 
            ''' with clients.</returns>            
            ''' <exception cref="ServiceConnectionException">Thrown  
            ''' when the local service is unable to accept the connection. 
            ''' </exception> 
            Public Function AcceptConnection() As Net.Sockets.NetworkStream

                Dim socket As Net.Sockets.Socket = Nothing
                Dim netwrkStream As Net.Sockets.NetworkStream = Nothing

                Try

                    socket = Me.serverSocket.Accept()
                    netwrkStream = New Net.Sockets.NetworkStream(socket, True)

                Catch exception As Exception

                    Dim servException As New ServiceConnectionException(SDPMessages.ErrorMsgAccConn + exception.Message)
                    Throw servException

                End Try

                Return netwrkStream

            End Function

#End Region

        End Class

    End Namespace

End Namespace
